package com.quanyan.place.web;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.quanyan.api.APIResponse;
import com.quanyan.api.enums.ApiResponseEnum;
import com.quanyan.common.utils.DateUtils;
import com.quanyan.orderpay.request.ReqPosUnionPayExcepVo;
import com.quanyan.orderpay.service.OrderPayService;
import com.quanyan.pay.enums.PayStatusEnum;
import com.quanyan.place.cache.PlaceRedisTemplate;
import com.quanyan.place.entity.apireq.ReqBillingInfo;
import com.quanyan.place.entity.apireq.ReqBusinessAccountVo;
import com.quanyan.place.entity.apireq.ReqExtractRecordVo;
import com.quanyan.place.entity.apireq.ReqOrderSetterVo;
import com.quanyan.place.entity.apireq.ReqPlaceOrderDetailVo;
import com.quanyan.place.entity.apireq.ReqPlaceOrderSearchVo;
import com.quanyan.place.entity.apireq.ReqPlaceSalePlan;
import com.quanyan.place.entity.apireq.ReqPlaceScanOrderSearchVo;
import com.quanyan.place.entity.apireq.ReqRevenueVo;
import com.quanyan.place.enums.PlaceErrorCodeEnum;
import com.quanyan.place.service.ApiPlaceService;
import com.quanyan.place.service.ApiPosUnionPayService;
import com.quanyan.place.service.PlaceMemberService;
import com.quanyan.place.service.PlaceOrderService;
import com.quanyan.place.service.PlaceOrderUtilService;
import com.quanyan.place.service.UpdateItemSalePriceService;
import com.quanyan.place.wrapper.PlaceOrderServiceWrapper;


/**
 * Created by zhaohui on 2016/6/2.
 * 订单管理模块
 */
@RestController
//@RequestMapping("/placeOrder")
@RequestMapping("/admin/api/place/order")
public class PlaceOrderController {
    private final static Logger logger = LoggerFactory.getLogger(PlaceOrderController.class);

    private final static int SCAN_POS_BAR_CODE_FAIL=0;
    private final static int SCAN_POS_BAR_CODE_SUCCESS=1;

    @Autowired
    PlaceOrderService placeOrderService;

    @Autowired
    ApiPlaceService apiPlaceService;

    @Autowired
    PlaceOrderServiceWrapper placeOrderServiceWrapper;

    @Autowired
    PlaceOrderUtilService placeOrderUtilService;
    
    @Autowired
    UpdateItemSalePriceService updateItemSalePriceService;
    
    @Autowired
    private OrderPayService orderPayService;

    @Autowired
    private PlaceRedisTemplate placeCache;
    
    @Autowired
    private ApiPosUnionPayService posUnionPayService;
    
    @Autowired
    private PlaceMemberService placeMemberService;
    
    /**
     * 后台订单管理列表 新
     * @param reqPlaceOrderSearchVo
     * @return
     */
    @RequestMapping(value = "/placeOrderMessage" ,method = RequestMethod.POST,produces = {"application/json; charset=UTF-8"})
    @ResponseBody
    public APIResponse placeOrderMessageList(@RequestBody @Valid ReqPlaceOrderSearchVo reqPlaceOrderSearchVo){
        return APIResponse.returnSuccess(placeOrderService.getPlaceOrderMessageList(reqPlaceOrderSearchVo));

    }
    /**
     * 根据订单id查询详情
     * @param placeOrderSearchVo
     * @return
     */
    @RequestMapping(value = "/placeOrderDetail" ,method = RequestMethod.POST,produces = {"application/json; charset=UTF-8"})
    @ResponseBody
    public APIResponse placeOrderMessageDetail(@RequestBody @Valid ReqPlaceOrderDetailVo placeOrderSearchVo,BindingResult bindingResult){
        return APIResponse.returnSuccess( placeOrderService.placeOrderMessageDetail(placeOrderSearchVo));
    }

    /**
     * 是否是会员订单
     * @return
     */
    @RequestMapping(value = "/isMemberOrder" ,method = RequestMethod.POST,produces = {"application/json; charset=UTF-8"})
    @ResponseBody
    public APIResponse placeOrderMessageList(@RequestBody @Valid Map<String, Object> map, BindingResult bindingResult){
        if (bindingResult.hasErrors()) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
        }
        String placeOrderId =  MapUtils.getString(map, "placeOrderId");
        if (StringUtils.isEmpty(placeOrderId)){
            return APIResponse.returnFail("placeOrderId为空！");
        }
        return placeOrderService.isMemberOrderByPlaceOrderId(placeOrderId);
    }

    /**
     * 后台扫描支付订单管理列表
     * @param reqPlaceScanOrderSearchVo
     * @return
     */
    @RequestMapping(value = "/placeScanOrder" ,method = RequestMethod.POST,produces = {"application/json; charset=UTF-8"})
    @ResponseBody
    public APIResponse placeScanOrder(@RequestBody @Valid ReqPlaceScanOrderSearchVo reqPlaceScanOrderSearchVo){
        return APIResponse.returnSuccess(placeOrderService.queryPlaceScanOrderList(reqPlaceScanOrderSearchVo));

    }

    /**
     * 条件查询
     * placeOrderCondition
     * @return
     */
    @RequestMapping(value = "/placeOrderCondition" ,method = RequestMethod.POST,produces = {"application/json; charset=UTF-8"})
    @ResponseBody
    public APIResponse placeOrderCondition(){
        return APIResponse.returnSuccess(placeOrderService.getOrderCondition(null));
    }

    /**
     * 条件查询(订单管理)
     * placeOrderCondition
     * @return
     */
    @RequestMapping(value = "/placeOrderConditionForOrderManager" ,method = RequestMethod.POST,produces = {"application/json; charset=UTF-8"})
    @ResponseBody
    public APIResponse placeOrderConditionForOrderManager(@RequestBody Map<String,Object> map){
        Integer businessMode = MapUtils.getInteger(map, "businessMode");
        return APIResponse.returnSuccess(placeOrderService.getOrderCondition(businessMode));
    }

    /**
     * 场馆订单列表导出 新
     * @param reqPlaceOrderSearchVo
     * @param bindingResult
     * @return
     */
    @RequestMapping(value = "/placeOrderMessageListExport" ,method = RequestMethod.POST,produces = {"application/json; charset=UTF-8"})
    @ResponseBody
    public APIResponse placeOrderMessageListExport(@RequestBody @Valid ReqPlaceOrderSearchVo reqPlaceOrderSearchVo,BindingResult bindingResult){
        return APIResponse.returnSuccess(placeOrderService.getPlaceOrderMessageListExport(reqPlaceOrderSearchVo));
    }

    /**
     * 商家端获取订场计划及销售情况
     * @param reqPlaceSalePlan
     * @return
     */
    @RequestMapping(value = "/placeSaleUnitPlan")
    public APIResponse<?> placeSaleUnitPlan(@RequestBody ReqPlaceSalePlan reqPlaceSalePlan){
        return apiPlaceService.getRespPlaceUnitSalePlanDetail(reqPlaceSalePlan);
    }

    /**
     * 商家端包场--支付下单
     * @param reqBillingInfo
     * @return
     */
    @RequestMapping(value = "/placeBookAll")
    public APIResponse<?> placeBookAll(@RequestBody ReqBillingInfo reqBillingInfo){
        try {
            return apiPlaceService.placeBookAll(reqBillingInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return APIResponse.returnFail(e.getMessage());
        }
    }
    
    /**
     * 商家端包场--预定下单(散客,会员)
     * @param reqBillingInfo
     * @return
     */
    @RequestMapping(value = "/placeBlockBook")
    public APIResponse<?> placeBlockBook(@RequestBody @Valid ReqBillingInfo reqBillingInfo){
        try {
        	return apiPlaceService.placeBlockBook(reqBillingInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return APIResponse.returnFail(e.getMessage());
        }
    }
    
    /**
     * 商家端锁单
     * @return
     */
    @RequestMapping(value = "/placeLockOrUnlockUnits")
    public APIResponse placeLockOrUnlockUnits(@RequestBody @Valid Map<String,Object> map, BindingResult bindingResult){
        if (bindingResult.hasErrors()) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
        }
        String strids = MapUtils.getString(map, "unitids");
        String lockRemarks = MapUtils.getString(map, "lockRemarks");
        String uid = MapUtils.getString(map,"uid");
        if (StringUtils.isEmpty(strids)){
            return APIResponse.returnFail("没有选择锁单的场地单元");
        }
        String[] ids1 = org.apache.commons.lang3.StringUtils.split(strids, ",");
        List<String> list = Arrays.asList(ids1);

        boolean flag = apiPlaceService.updateTbBizPlaceUnitSalePlan(list , MapUtils.getByte(map, "state"), lockRemarks,uid);
        if (flag){
            return APIResponse.returnSuccess(ApiResponseEnum.SUCCESS);
        }
        return APIResponse.returnFail("操作失败");
    }

    /**
     * 商家端开单
     * @param reqBillingInfo
     * @return
     */
    @RequestMapping(value = "/placeBilling")
    public APIResponse<?> placeBilling(@RequestBody @Valid ReqBillingInfo reqBillingInfo){
        if (StringUtils.isEmpty(reqBillingInfo.getPlaceUnitId())){
            return APIResponse.returnFail("没有选择开单的场地单元");
        }
        APIResponse response = null;
        try {
            response = apiPlaceService.placeBillingPlus(reqBillingInfo);
        } catch (Exception e) {
            return APIResponse.returnFail(e.getMessage());
        }
        return response;
    }

    /**
     * 商家端预定
     * @param reqBillingInfo
     * @return
     */
    @RequestMapping(value = "/placeBook")
    public APIResponse<?> placeBook(@RequestBody @Valid ReqBillingInfo reqBillingInfo){
        if (StringUtils.isEmpty(reqBillingInfo.getPlaceUnitId())){
            return APIResponse.returnFail("没有选择开单的场地单元");
        }
        APIResponse<?> response = null;
            try {
            if(StringUtils.isEmpty(reqBillingInfo.getMemberCardId())){
                response = apiPlaceService.placeBookPlus(reqBillingInfo);
            }else{
                response = apiPlaceService.placeBookForMemberPlus(reqBillingInfo);
            }
        } catch (Exception e) {
            return APIResponse.returnFail(e.getMessage());
        }
        return response;
    }

    /**
     * 商家端取消预订
     * @param map
     * @return
     */
    @RequestMapping(value = "/placeCancelBook")
    public APIResponse<?> placeCancelBook(@RequestBody @Valid Map<String,Object> map, BindingResult bindingResult){
        if (bindingResult.hasErrors()) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
        }
        String reqPlaceOrderId = MapUtils.getString(map, "reqPlaceOrderId");
        if (StringUtils.isEmpty(reqPlaceOrderId)){
            return APIResponse.returnFail("没有指定OrderId");
        }
        APIResponse response = apiPlaceService.placeCancelBook(reqPlaceOrderId);
        if (response.isRet()){
            return response;
        }
        return APIResponse.returnFail("取消失败");
    }

    /**
     * 商家端支付4
     * @param map
     * @return
     */
    @RequestMapping(value = "/placePay")
    public APIResponse<?> placePay(@RequestBody @Valid Map<String,Object> map, BindingResult bindingResult){
        if (bindingResult.hasErrors()) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
        }
        String reqPlaceOrderId = MapUtils.getString(map, "reqPlaceOrderId");
        Integer adminPayType = MapUtils.getInteger(map, "adminPayType");
        String receivedAmount = MapUtils.getString(map, "receivedAmount");
        String memo = MapUtils.getString(map,"memo");
        String expression = MapUtils.getString(map,"expression");
        String scanCode = MapUtils.getString(map,"scanCode");
        if (StringUtils.isEmpty(reqPlaceOrderId)){
            return APIResponse.returnFail("没有指定OrderId");
        }
        if (StringUtils.isEmpty(adminPayType)){
            return APIResponse.returnFail("请选择商家端支付方式");
        }
        if (StringUtils.isEmpty(receivedAmount)){
            return APIResponse.returnFail("实付金额不能为空");
        }
        if (StringUtils.isEmpty(expression)){
            expression = "";
        }
        try {
            return apiPlaceService.placePay(reqPlaceOrderId,adminPayType,receivedAmount,memo,expression,scanCode);
        } catch (Exception e) {
            return APIResponse.returnFail(e.getMessage());
        }
    }
    
    /**
     * 商家端包场子订单取消预订
     * @param map
     * @return
     */
    @RequestMapping(value = "/placeBlockCancelBook")
    public APIResponse<?> placeBlockCancelBook(@RequestBody @Valid Map<String,Object> map, BindingResult bindingResult){
        if (bindingResult.hasErrors()) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
        }
        String reqPlaceOrderId = MapUtils.getString(map, "reqPlaceOrderId");
        if (StringUtils.isEmpty(reqPlaceOrderId)){
            return APIResponse.returnFail("没有指定OrderId");
        }
        return apiPlaceService.placeBlockCancelBook(reqPlaceOrderId);
    }
    
    /**
     * 商家端包场子订单支付
     * @param map
     * @return
     */
    @RequestMapping(value = "/placeBlockPay")
    public APIResponse<?> placeBlockPay(@RequestBody @Valid Map<String,Object> map, BindingResult bindingResult){
        if (bindingResult.hasErrors()) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
        }
        String reqPlaceOrderId = MapUtils.getString(map, "reqPlaceOrderId");
        Integer adminPayType = MapUtils.getInteger(map, "adminPayType");
        String receivedAmount = MapUtils.getString(map, "receivedAmount");
        String memo = MapUtils.getString(map,"memo");
        String expression = MapUtils.getString(map,"expression");
        String scanCode = MapUtils.getString(map,"scanCode");
        if (StringUtils.isEmpty(reqPlaceOrderId)){
            return APIResponse.returnFail("没有指定OrderId");
        }
        if (StringUtils.isEmpty(adminPayType)){
            return APIResponse.returnFail("请选择商家端支付方式");
        }
        if (StringUtils.isEmpty(receivedAmount)){
            return APIResponse.returnFail("实付金额不能为空");
        }
        if (StringUtils.isEmpty(expression)){
            expression = "";
        }
        try {
            return apiPlaceService.placeBlockPay(reqPlaceOrderId,adminPayType,receivedAmount,memo,expression,scanCode);
        } catch (Exception e) {
            return APIResponse.returnFail(e.getMessage());
        }
    }
    
    /**
     * 商家端包场子订单退款 --  后面切到明细退款新接口
     * @param map
     * @return
     */
    @RequestMapping(value = "/placeBlockRefund")
    public APIResponse<?> placeBlockRefund(@RequestBody @Valid Map<String,Object> map, BindingResult bindingResult){
        if (bindingResult.hasErrors()) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
        }
        String reqPlaceOrderId = MapUtils.getString(map, "reqPlaceOrderId");
        Integer operateUid = MapUtils.getInteger(map, "uid");
        Integer customerId = MapUtils.getInteger(map, "customerId");
        Integer placeId = MapUtils.getInteger(map, "placeId");
        if (StringUtils.isEmpty(reqPlaceOrderId)){
            return APIResponse.returnFail("没有指定OrderId");
        }
        if (StringUtils.isEmpty(placeId)){
            return APIResponse.returnFail("placeId为null");
        }
        try {
            return placeOrderServiceWrapper.placeBlockRefund(reqPlaceOrderId,operateUid,placeId,customerId);
        } catch (Exception e) {
            e.printStackTrace();
            return APIResponse.returnFail(e.getMessage());
        }
    }

    /**
     * 商家端退款
     * @param map
     * @return
     */
    @RequestMapping(value = "/placeRefund")
    public APIResponse<?> placeRefund(@RequestBody @Valid Map<String,Object> map, BindingResult bindingResult){
        if (bindingResult.hasErrors()) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
        }
        String reqPlaceOrderId = MapUtils.getString(map, "reqPlaceOrderId");
        Integer operateUid = MapUtils.getInteger(map, "uid");
        Integer customerId = MapUtils.getInteger(map, "customerId");
        Integer placeId = MapUtils.getInteger(map, "placeId");
        if (StringUtils.isEmpty(reqPlaceOrderId)){
            return APIResponse.returnFail("没有指定OrderId");
        }
        if (StringUtils.isEmpty(placeId)){
            return APIResponse.returnFail("placeId为null");
        }
        try {
            return placeOrderServiceWrapper.placeRefund(reqPlaceOrderId,operateUid,placeId,customerId);
        } catch (Exception e) {
            e.printStackTrace();
            return APIResponse.returnFail(e.getMessage());
        }
    }

    /**
     * 营收统计
     * @param reqRevenueVo
     * @param bindingResult
     * @return
     */
    @RequestMapping(value = "/getRevenueStatistics" ,method = RequestMethod.POST,produces = {"application/json; charset=UTF-8"})
    @ResponseBody
    public APIResponse getRevenueStatistics(@RequestBody ReqRevenueVo reqRevenueVo,BindingResult bindingResult){
        return APIResponse.returnSuccess(placeOrderService.getPlaceOrderAmountStats(reqRevenueVo));
        //return APIResponse.returnSuccess(placeOrderService.getRevenueStatistics(reqRevenueVo));
    }

    /**
     * 场地利用率统计
     * @param reqRevenueVo
     * @param bindingResult
     * @return
     */
    @RequestMapping(value = "/getPlaceUtilizationStatistics" ,method = RequestMethod.POST,produces = {"application/json; charset=UTF-8"})
    @ResponseBody
    public APIResponse getPlaceUtilizationStatistics(@RequestBody ReqRevenueVo reqRevenueVo,BindingResult bindingResult){
        return APIResponse.returnSuccess(placeOrderService.getPlaceUtilizationStatistics(reqRevenueVo));
    }

    /**
     * 商家端会员开单5
     * @param reqBillingInfo
     * @return
     */
    @RequestMapping(value = "/placeBillingForMember")
    public APIResponse<?> placeBillingForMember(@RequestBody @Valid ReqBillingInfo reqBillingInfo) {
        if (StringUtils.isEmpty(reqBillingInfo.getPlaceUnitId())){
            return APIResponse.returnFail("没有选择开单的场地单元");
        }
        APIResponse<?> response = null;
        try {
            response = apiPlaceService.placeBillingForMemberPlus(reqBillingInfo);
        } catch (Exception e) {
            return  APIResponse.returnFail(e.getMessage());
        }
        return response;
    }

    /**
     * 商家端会员包场6
     * @param reqBillingInfo
     * @return
     */
   @RequestMapping(value = "/placeBookAllForMember")
    public APIResponse<?> placeBookAllForMember(@RequestBody @Valid ReqBillingInfo reqBillingInfo){
        if (StringUtils.isEmpty(reqBillingInfo.getPlaceUnitId())){
            return APIResponse.returnFail("没有选择开单的场地单元");
        }
       try {
           return apiPlaceService.placeBookAllForMember(reqBillingInfo);
       } catch (Exception e) {
           return APIResponse.returnFail(e.getMessage());
       }
   }

    /**
     * 商家端开单获取会员卡列表
     * @param map
     * @param bindingResult
     * @return
     */
    @RequestMapping(value = "/billingPlaceGetMemberCardList")
    public APIResponse<?> billingPlaceGetMemberCardList(@RequestBody @Valid Map<String,Object> map, BindingResult bindingResult){
        if (bindingResult.hasErrors()) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
        }
        String userName = MapUtils.getString(map, "userName");
        String phone = MapUtils.getString(map, "phone");
        Integer placeId = MapUtils.getInteger(map, "placeId");
        Integer categoryId = MapUtils.getInteger(map, "categoryId");
        if (StringUtils.isEmpty(phone)){
            return APIResponse.returnFail("phone is null");
        }
        if (StringUtils.isEmpty(placeId)){
            return APIResponse.returnFail("placeId is null");
        }
        return apiPlaceService.billingPlaceGetMemberCardList(userName,phone,placeId,categoryId);
    }
    
    /**
     * 商家端开单 根据手机号、姓名模糊查询获取会员卡列表
     * @param map
     * @param bindingResult
     * @return
     */
    @RequestMapping(value = "/queryMemberCardList")
    public APIResponse<?> queryMemberCardList(@RequestBody @Valid Map<String,Object> map, BindingResult bindingResult){
        if (bindingResult.hasErrors()) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
        }
        try {
        	 String key = MapUtils.getString(map, "key");
             Integer placeId = MapUtils.getInteger(map, "placeId");
             Integer categoryId = MapUtils.getInteger(map, "categoryId");
             
             Assert.notNull(key, "请输入手机号或姓名");
             Assert.notNull(placeId, "场馆编号不能为空");
             Assert.notNull(categoryId, "运动类型不能为空");
             
             return APIResponse.returnSuccess(placeMemberService.queryMemberCardList(key,placeId,categoryId));
		} catch (IllegalArgumentException arge){
			logger.warn("传入参数不合法", arge);
			return APIResponse.returnFail(arge.getMessage());
		} catch (Exception e) {
			logger.error("查询会员卡失败", e);
			return APIResponse.returnFail(e.getMessage());
		}
    }

    /**
     * 商家端支付方式
     * @return Map
     */
    @RequestMapping(value = "/getAdminPayWays", method = RequestMethod.POST)
    @ResponseBody
    public APIResponse<?> getAdminPayWays(/*@RequestParam(value = "userType",required = false) Integer userType*/@RequestBody(required = false) @Valid Map<String,Object> map){
        if (MapUtils.isEmpty(map)){
            return APIResponse.returnFail("参数异常！");
        }
        Integer placeId = MapUtils.getInteger(map,"placeId");
        Integer userType = MapUtils.getInteger(map, "userType");
        Boolean isRecharge = MapUtils.getBoolean(map, "isRecharge");
        if (StringUtils.isEmpty(placeId)){
            return APIResponse.returnFail("placeId必传");
        }
        if (StringUtils.isEmpty(isRecharge)){
            return apiPlaceService.getAdminPayWaysDictDisplayName(placeId,userType, false);
        }
        return apiPlaceService.getAdminPayWaysDictDisplayName(placeId,userType, isRecharge);
    }

    @RequestMapping(value = "/pollingOrderStatus")
    public APIResponse<?> pollingOrderStatus(@RequestBody @Valid Map<String,Object> map, BindingResult bindingResult){
        if (bindingResult.hasErrors()) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
        }
        String placeOrderId = MapUtils.getString(map, "placeOrderId");
        if (StringUtils.isEmpty(placeOrderId)){
            return APIResponse.returnFail(PlaceErrorCodeEnum.ORDER_ID_REQUIRED);
        }
        return placeOrderServiceWrapper.pollingOrderStatus(placeOrderId);
    }

    @RequestMapping(value = "/printOrderInfo")
    public APIResponse<?> printOrderInfo(@RequestBody @Valid Map<String,Object> map, BindingResult bindingResult){
        if (bindingResult.hasErrors()) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
        }
        String placeOrderId = MapUtils.getString(map, "placeOrderId");
        if (StringUtils.isEmpty(placeOrderId)){
            return APIResponse.returnFail(PlaceErrorCodeEnum.ORDER_ID_REQUIRED);
        }
        return APIResponse.returnSuccess(placeOrderUtilService.printOrderInfo(placeOrderId));
    }


    @RequestMapping(value = "/orderSetterList", method = RequestMethod.POST)
    public APIResponse<?> orderSetterList(@RequestBody @Valid ReqOrderSetterVo reqOrderSetterVo,BindingResult bindingResult){
        if (bindingResult.hasErrors()) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
        }
        if (reqOrderSetterVo!=null){
            return placeOrderServiceWrapper.orderSetterList(reqOrderSetterVo);
        }else{
            return APIResponse.returnFail("参数不能为空");
        }

    }

    @RequestMapping(value = "/orderSetterTask", method = RequestMethod.POST)
    public APIResponse<?> orderSetterTask(){
             placeOrderServiceWrapper.orderSetterTask();
                return null;
    }

    @RequestMapping(value = "/orderSetterOperate", method = RequestMethod.POST)
    public APIResponse<?> orderSetterOperate(@RequestBody @Valid ReqOrderSetterVo reqOrderSetterVo,BindingResult bindingResult){
        if (bindingResult.hasErrors()) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
        }
        if (reqOrderSetterVo!=null){
            //try {
            return  placeOrderServiceWrapper.orderSetterOperate(reqOrderSetterVo);
           // }catch (Exception e){
             //   return APIResponse.returnFail("提现异常"+e.getMessage());
            //}
        }else{
            return APIResponse.returnFail("参数不能为空");
        }
    }


    @RequestMapping(value = "/extractRecordList", method = RequestMethod.POST)
    public APIResponse<?> extractRecordList(@RequestBody @Valid ReqExtractRecordVo reqExtractRecordVo,BindingResult bindingResult){
        if (bindingResult.hasErrors()) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
        }
        if (reqExtractRecordVo!=null){
            try {
             return   placeOrderServiceWrapper.extractRecordList(reqExtractRecordVo);
            }catch (Exception e){
                return APIResponse.returnFail("提现异常"+e.getMessage());
            }
        }else{
            return APIResponse.returnFail("参数不能为空");
        }
    }

    @RequestMapping(value = "/businessCheckAccount", method = RequestMethod.POST)
    public APIResponse<?> businessCheckAccount(@RequestBody @Valid ReqBusinessAccountVo reqVo,BindingResult bindingResult){
        if (bindingResult.hasErrors()) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
        }
        if (reqVo!=null){
            //try {
                return   placeOrderServiceWrapper.businessCheckAccount(reqVo);
           // }catch (Exception e){
            //    return APIResponse.returnFail("提现异常"+e.getMessage());
         //   }
        }else{
            return APIResponse.returnFail("参数不能为空");
        }
    }

    /**
     * 根据场馆Id获取供应商银行账号
     * @param reqVo
     * @param bindingResult
     * @return
     */
    @RequestMapping(value = "/getAccountInfoByPlaceId", method = RequestMethod.POST)
    public APIResponse<?> getAccountInfoByPlaceId(@RequestBody @Valid ReqBusinessAccountVo reqVo,BindingResult bindingResult){
        if (bindingResult.hasErrors()) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
        }
        if (reqVo!=null){
            //try {
            return   placeOrderServiceWrapper.getAccountInfoByPlaceId(reqVo.getSupplierId());
            // }catch (Exception e){
            //    return APIResponse.returnFail("获取异常"+e.getMessage());
            //   }
        }else{
            return APIResponse.returnFail("参数不能为空");
        }
    }


    /**
     * 根据场馆Id获取供应商银行账号
     * @param reqVo
     * @param bindingResult
     * @return
     */
    @RequestMapping(value = "/getPlaceBySupplierId", method = RequestMethod.POST)
    public APIResponse<?> getPlaceBySupplierId(@RequestBody @Valid ReqBusinessAccountVo reqVo,BindingResult bindingResult){
        if (reqVo!=null){
            //try {
            return   placeOrderServiceWrapper.getPlaceBySupplierId(reqVo.getSupplierId());
            // }catch (Exception e){
            //    return APIResponse.returnFail("获取异常"+e.getMessage());
            //   }
        }else{
            return APIResponse.returnFail("参数不能为空");
        }
    }

    /**
     * 根据提现流水号更新提现信息
     * @param reqVo
     * @param bindingResult
     * @return
     */
    @RequestMapping(value = "/updateExtractInfoByExtractNo", method = RequestMethod.POST)
    public APIResponse<?> updateExtractInfoByExtractNo(@RequestBody @Valid ReqExtractRecordVo reqVo,BindingResult bindingResult) {
        if (reqVo != null) {
            //try {
            // return   placeOrderServiceWrapper.updateExtractInfoByExtractNo(reqVo);
            // }catch (Exception e){
            //    return APIResponse.returnFail("获取异常"+e.getMessage());
            //   }
            // }else{
            //return APIResponse.returnFail("参数不能为空");
            //  }
        }
        return null;
    }

    /**
     * 批量更新历史订单真实价格（sale_price）
     * @return
     */
    @RequestMapping(value = "/batchUpdatePlaceOrderPrice", method = RequestMethod.POST)
    public APIResponse batchUpdateHistoryPlaceOrderPrice() {
    	updateItemSalePriceService.updatePlaceOrderItemSalePrice();
    	return APIResponse.returnSuccess();
    }

   /**
    * 银联pos异常，通过条形码处理
    * @param posBarCode
    * @param orderNo
    * @param uid
    * @param isBookAll 0:否，1：是
    * @return
    */
	@RequestMapping(value = "/posUPayExcepByBarCode" ,method = RequestMethod.POST,produces = {"application/json; charset=UTF-8"})
    @ResponseBody
    public APIResponse posUnionPayExcepByBarCode(@RequestParam(value = "posBarCode", required = true) String posBarCode,@RequestParam(value = "orderNo", required = true) String orderNo,@RequestParam(value = "uid", required = true) String uid,@RequestBody Map<String,Object> map){
        String submitTime=DateUtils.getStandardCurrentTime();
        
        String isBookAll=MapUtils.getString(map,"isBookAll");
        if(org.apache.commons.lang3.StringUtils.isEmpty(isBookAll)){
        	isBookAll="0";
        }
        
        if(StringUtils.isEmpty(posBarCode)||posBarCode.length()!=16){
        	  return APIResponse.returnFail("输入pos小票参考号不合法!");
        }
        logger.info("银联pos异常,扫条形码处理,调用posUnionPayExcepByBarCode()传入参数，操作员：{}，参考号:{} ",uid,posBarCode );
        logger.info("orderNo:"+orderNo+",isBookAll:"+isBookAll);
        String orderNoSuffix=posBarCode.substring(0,4);//支付中心订单号后4位
		String referenceNo=posBarCode.substring(4, posBarCode.length());// 银联交易参考
		
		
		try {
			Integer uidTmp=Integer.parseInt(uid);
			//1.验证pos小票条形码生成规则
	    	List<String> orderNos=posUnionPayService.selectPosUnionOrderNo(orderNoSuffix,uidTmp,isBookAll); 
	        if(StringUtils.isEmpty(orderNos)||orderNos.size()==0){
	        	   return APIResponse.returnFail("验证不通过，请输入正确条形码");
	        }
	        
       	 //2.修改本地系统中订单状态为已付款
	         int  updateStatus=posUnionPayService.updatePosUnionOrderStatus(uidTmp,orderNo,DateUtils.tranferStringToDate(submitTime));
	         if(updateStatus>0){//异常pos订单处理成功
	        	 //更改本地库存状态
	        	 posUnionPayService.updateInventoryStatus(orderNo,isBookAll);
	             logger.info("银联pos异常,扫条形码修改订单状态成功" );
	           
	         }else{
	        	 logger.info("银联pos异常,扫条形码修改订单状态失败" );
	         }

		//3.记录异常订单到支付中心	        		
		 ReqPosUnionPayExcepVo unionPayExcepVo=new ReqPosUnionPayExcepVo();
         unionPayExcepVo.setOperator(String.valueOf(uid));//操作员uid
         unionPayExcepVo.setOrderStatus(PayStatusEnum.PAY_STATE_PAYED.getId());
         unionPayExcepVo.setReferenceNo(referenceNo);
         unionPayExcepVo.setOrderNo(orderNo);
         unionPayExcepVo.setSubmitTime(submitTime);
        
         int payCenterstatus=orderPayService.posUnionPayExcepton(unionPayExcepVo);
         if(payCenterstatus==1){
       	 logger.info("银联pos异常,调用支付中心记录异常订单成功。");
        }else{
       	 logger.info("银联pos异常,调用支付中心记录异常订单失败。");
        }
       
         return APIResponse.returnSuccess();

        }catch (Exception e){
            logger.error("调用支付中心:银联pos异常,扫条形码处理异常,"+e.getMessage());
            return APIResponse.returnFail(e.getMessage());

        }

    }

    /**
     * 获取扫描条形码状态
     * @param posBarCode pos条形码
     * @return 0：扫码失败，1：扫码成功
     */
    @RequestMapping(value = "/scanPosBarCodeStatus" ,method = RequestMethod.POST,produces = {"application/json; charset=UTF-8"})
    @ResponseBody
    public APIResponse scanPosBarCodeStatus(@RequestParam(value = "posBarCode", required = true) String posBarCode){
        logger.info("获取扫描pos条形码状态传入，条形码:{}",posBarCode);
        Map<String,Integer> data=new HashMap<>();
        String posBarCodeStatus=placeCache.getString("IS_SCAN_ORDER_NO_"+posBarCode);
            if(null!=posBarCodeStatus){
            	logger.info("获取扫描pos条形码状态成功");
                placeCache.delteKey("IS_SCAN_ORDER_NO_"+posBarCode);
                data.put("barCodeStatus",SCAN_POS_BAR_CODE_SUCCESS);
                return APIResponse.returnSuccess(data);
            }
            logger.info("获取扫描pos条形码状态失败");
        data.put("barCodeStatus",SCAN_POS_BAR_CODE_FAIL);
        return APIResponse.returnSuccess(data);

    }
    /**
     * 获取pos支付状态
     * @param posBarCode pos条形码(支付中心订单号)
     * @param isMember 0:(开单、门票、商品)，1：(会员) 3：包场开单
     * @return 0：支付失败，1：支付成功
     */
    @RequestMapping(value = "/getPosPayStatus" ,method = RequestMethod.POST,produces = {"application/json; charset=UTF-8"})
    @ResponseBody
    public APIResponse getPosPayStatus(@RequestParam(value = "posBarCode", required = true) String posBarCode,@RequestParam(value = "isMember", required = true) String isMember){
        logger.info("获取扫描pos条形码状态传入，条形码:{}",posBarCode);
        Map<String,Object> data=new HashMap<>();
        String placeOrderId="";
        if(isMember.equals("0")){
        	placeOrderId=posUnionPayService.getPosUnionPlaceOrderId(posBarCode);
        }else if(isMember.equals("1")){
        	placeOrderId=posUnionPayService.getPosUnionMemberOrderId(posBarCode);
        }else{
        	placeOrderId=posUnionPayService.getBookAllPlaceOrderId(posBarCode);
        	
        }
       
       if(org.apache.commons.lang.StringUtils.isNotEmpty(placeOrderId)){
    	   logger.info("扫描pos条形码支付成功");
           data.put("payStatus",SCAN_POS_BAR_CODE_SUCCESS);
           data.put("placeOrderId", placeOrderId);
           if(isMember.equals("3")){//包场开单
        	   data.put("bookData",placeOrderUtilService.printBookAllOrderInfo(placeOrderId));  
           }
           
         
           
           return APIResponse.returnSuccess(data);
       }
            logger.info("扫描pos条形码支付失败");
        data.put("payStatus",SCAN_POS_BAR_CODE_FAIL);
        return APIResponse.returnSuccess(data);

    }

    /**
     * 购物车订单详情展示
     * @param map
     * @param bindingResult
     * @return
     */
    @RequestMapping(value = "/getPlaceOrderDetail")
    public APIResponse<?> getPlaceOrderDetail(@RequestBody @Valid Map<String,Object> map, BindingResult bindingResult){
        if (bindingResult.hasErrors()) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
        }
        String placeOrderId = MapUtils.getString(map, "placeOrderId");
        if (StringUtils.isEmpty(placeOrderId)){
            return APIResponse.returnFail(PlaceErrorCodeEnum.ORDER_ID_REQUIRED);
        }
        return placeOrderServiceWrapper.getPlaceOrderDetail(placeOrderId);
    }

    /**
     * 购物车取消预订
     * @param map
     * @return
     */
    @RequestMapping(value = "/placeCancelShoppingCard")
    public APIResponse<?> placeCancelShoppingCard(@RequestBody @Valid Map<String,Object> map, BindingResult bindingResult){
        if (bindingResult.hasErrors()) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
        }
        String reqPlaceOrderId = MapUtils.getString(map, "placeOrderId");
        if (StringUtils.isEmpty(reqPlaceOrderId)){
            return APIResponse.returnFail("没有指定OrderId");
        }
        return placeOrderService.placeCancelShoppingCard(reqPlaceOrderId);
    }

    /**
     * 购物车订单退款
     * @param map
     * @return
     */
    @RequestMapping(value = "/placeRefundShoppingCard")
    public APIResponse<?> placeRefundShoppingCard(@RequestBody @Valid Map<String,Object> map, BindingResult bindingResult){
        if (bindingResult.hasErrors()) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
        }
        String placeOrderId = MapUtils.getString(map, "placeOrderId");
        Integer operateUid = MapUtils.getInteger(map, "operateUid");

        if (StringUtils.isEmpty(placeOrderId)){
            return APIResponse.returnFail("placeOrderId must input");
        }
        if (StringUtils.isEmpty(operateUid)){
            return APIResponse.returnFail("operateUid must input");
        }
        try {
            return placeOrderService.placeRefundShoppingCard(placeOrderId,operateUid);
        } catch (Exception e) {
            return APIResponse.returnFail(e.getMessage());
        }
    }
}
